package com.sig.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 转化工具
 *
 * @author sig
 * @since 2019/1/25
 */
public final class ConvertUtil {

    private ConvertUtil() {
    }

    public static String dirtyWordConvert(final String text) {
        List<String> list = new ArrayList<>();
        Reader reader = null;
        BufferedReader bReader = null;
        try {
            reader = new FileReader("./dirtyWord.txt");
            bReader = new BufferedReader(reader);
            for (String str; (str = bReader.readLine()) != null; )
                list.add(str);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (bReader != null) {
                try {
                    bReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String convertTest = "";
        for (String str : list) {
            Pattern pattern = Pattern.compile(str, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(text);
            StringBuilder builder = new StringBuilder();
            while (matcher.find())
                matcher.appendReplacement(builder, calcAsteriskAmount(str.length()));
            matcher.appendTail(builder);
            convertTest = builder.toString();
        }
        return convertTest;
    }

    private static String calcAsteriskAmount(int length) {
        StringBuilder amount = new StringBuilder(length);
        for (int pos = 0; pos < length; pos++)
            amount.append("*");
        return amount.toString();
    }
}
